package db

import (
	"encoding/json"
	"fmt"
	"modbusComm/model"
	"os"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
)

var db *gorm.DB

type DbConfig struct {
	Host        string
	User        string
	Password    string
	Dbname      string
	Port        int64
	AutoMigrate bool
}

func init() {
	var dbConfig DbConfig

	f, err := os.Open("config/db.json")
	if err != nil {
		panic(err)
	}

	err = json.NewDecoder(f).Decode(&dbConfig)
	if err != nil {
		panic(err)
	}
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local", dbConfig.User, dbConfig.Password, dbConfig.Host, dbConfig.Port, dbConfig.Dbname)
	// dsn := fmt.Sprintf("host=%s user=%s password=%s dbname=%s port=%d sslmode=disable TimeZone=Asia/Shanghai", dbConfig.Host, dbConfig.User, dbConfig.Password, dbConfig.Dbname, dbConfig.Port)
	d, err := gorm.Open(mysql.Open(dsn), &gorm.Config{Logger: logger.Default.LogMode(logger.Info)})
	if err != nil {
		panic("failed to connect database")
	}
	if dbConfig.AutoMigrate {
		d.AutoMigrate(&model.UpsRunInfo{})
	}
	db = d
}
func GetDB() *gorm.DB {
	return db
}
